<template>
  <div class="screen-sharing" id="screen-sharing"></div>
</template>

<script>
import TRTC from "trtc-js-sdk";
const sdkAppId = 1400495479;

export default {
  data() {
    return {
      masterUserId: "userA", //写死主持人
      masterUserInfo: {
        userId: "userA",
      },
      userSig: "eJyrVgrxCdYrSy1SslIy0jNQ0gHzM1NS80oy0zLBwqXFqUXxphZGxobm5lD54pTsxIKCzBQlK0MTAwMTS1MTc0uITElmbipQ1MzQzNzI3MTCECKaWlGQWQQUNzMwsTAwgJqRmQ40vKCqIlg7x9-fu7jCszwnudQzJcopMsXE0zvUwNg5vDzAMSukyizT3SvKLNBWqRYAAnwy0w__",
      userId: "user_5823177",
      shareId: "",
      trtcRoomId: 888888,
      shareClient: null,
      localStream: null,
    };
  },
  computed: {},
  mounted() {
    // this.userId = this.$route.query.userId;
    // this.userSig = this.$route.query.userSig;
    // this.shareId = "share_" + this.userId;
    this.trtcRoomId = this.$route.query.trtcRoomId - 0; //房间id必须是数字
    this.init();
  },
  beforeDestroy() {},
  methods: {
    // 初始化音视频
    init(index) {
      let shareClient = TRTC.createClient({
        mode: "rtc",
        userId: this.userId,
        sdkAppId: sdkAppId, // 此处填写你的 sdkappid
        userSig: this.userSig,
      });
      this.shareClient = shareClient;
      shareClient.on("stream-added", (event) => {
        const remoteStream = event.stream;
        shareClient.unsubscribe(remoteStream);
      });
      shareClient.join({ roomId: this.trtcRoomId }).then(() => {
        // console.log("shareClient join success");
        // 创建屏幕分享流
        const localStream = TRTC.createStream({ audio: false, screen: true });
        this.localStream = localStream;
        localStream.initialize().then(() => {
          localStream.play("screen-sharing");
          // screencast stream init success
          shareClient.publish(localStream).then(() => {
            console.log("screen casting");
          });
        });
        // 屏幕分享流监听屏幕分享停止事件
        localStream.on("screen-sharing-stopped", (event) => {
          console.log("退出");
          // 关闭屏幕分享流
          localStream.close();
          // 屏幕分享客户端停止推流
          shareClient.unpublish(localStream);
          // 屏幕分享客户端退房
          // shareClient.leave();
          this.$emit("screenSharing");
        });
      });

      // 主 Client 中指定取消订阅 shareId 的远端流
      shareClient.on("stream-added", (event) => {
        console.log(12312312321321);
        const remoteStream = event.stream;
        const remoteUserId = remoteStream.getUserId();
        if (remoteUserId === this.shareId) {
          // 取消订阅自己的屏幕分享流
          shareClient.unsubscribe(remoteStream);
        } else {
          // 订阅其他一般远端流
          shareClient.subscribe(remoteStream);
        }
      });
    },
  },
};
</script>

<style  lang="scss">
.screen-sharing {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 999;
}
</style>
